package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TopicChangeRequest;
import com.ruoyi.system.domain.StudentInfo;
import com.ruoyi.system.domain.TeacherInfo;
import com.ruoyi.system.service.ITopicChangeRequestService;
import com.ruoyi.system.service.IStudentInfoService;
import com.ruoyi.system.service.ITeacherInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 选题变更申请Controller
 *
 * @author ltr
 * @date 2024-11-16
 */
@RestController
@RequestMapping("/system/topicChangeRequest")
public class TopicChangeRequestController extends BaseController
{
    @Autowired
    private ITopicChangeRequestService topicChangeRequestService;

    @Autowired
    private IStudentInfoService studentInfoService;

    @Autowired
    private ITeacherInfoService teacherInfoService;

    // ==================== 学生端接口 ====================

    /**
     * 查询当前学生的变更申请列表（学生端）
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/my/list")
    public AjaxResult myList()
    {
        Long studentId = getCurrentStudentId();
        if (studentId == null)
        {
            return error("请先完善学生信息");
        }

        List<TopicChangeRequest> list = topicChangeRequestService.selectChangeRequestListByStudentId(studentId);
        return success(list);
    }

    /**
     * 学生提交选题变更申请（学生端）
     */
    @PreAuthorize("@ss.hasRole('student')")
    @Log(title = "提交换题申请", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody TopicChangeRequest topicChangeRequest)
    {
        Long studentId = getCurrentStudentId();
        if (studentId == null)
        {
            return error("请先完善学生信息");
        }

        // 设置学生ID和创建人
        topicChangeRequest.setStudentId(studentId);
        topicChangeRequest.setCreateBy(getUsername());

        return toAjax(topicChangeRequestService.submitChangeRequest(topicChangeRequest));
    }

    /**
     * 学生取消变更申请（学生端）
     */
    @PreAuthorize("@ss.hasRole('student')")
    @Log(title = "取消换题申请", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{requestId}")
    public AjaxResult cancel(@PathVariable Long requestId)
    {
        Long studentId = getCurrentStudentId();
        if (studentId == null)
        {
            return error("请先完善学生信息");
        }

        return toAjax(topicChangeRequestService.cancelChangeRequest(requestId, studentId));
    }

    /**
     * 检查学生是否可以提交变更申请（学生端）
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/check/canSubmit")
    public AjaxResult checkCanSubmit()
    {
        Long studentId = getCurrentStudentId();
        if (studentId == null)
        {
            return error("请先完善学生信息");
        }

        boolean canSubmit = topicChangeRequestService.canStudentSubmitChangeRequest(studentId);
        return success(canSubmit);
    }

    /**
     * 查询变更申请详情（学生端）
     */
    @PreAuthorize("@ss.hasRole('student')")
    @GetMapping("/my/detail/{requestId}")
    public AjaxResult getMyDetail(@PathVariable Long requestId)
    {
        Long studentId = getCurrentStudentId();
        if (studentId == null)
        {
            return error("请先完善学生信息");
        }

        // 检查申请是否属于该学生
        if (!topicChangeRequestService.checkRequestOwner(requestId, studentId))
        {
            return error("无权查看该申请");
        }

        TopicChangeRequest request = topicChangeRequestService.selectTopicChangeRequestByRequestId(requestId);
        return success(request);
    }

    // ==================== 教师端接口 ====================

    /**
     * 查询当前教师需要审核的变更申请列表（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @GetMapping("/teacher/pendingList")
    public TableDataInfo teacherPendingList()
    {
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null)
        {
            return getDataTable(null);
        }

        startPage();
        // 合并原教师和新教师需要审核的列表
        List<TopicChangeRequest> oldTeacherList =
                topicChangeRequestService.selectPendingRequestsForOldTeacher(teacherId);
        List<TopicChangeRequest> newTeacherList =
                topicChangeRequestService.selectPendingRequestsForNewTeacher(teacherId);

        // 合并两个列表
        oldTeacherList.addAll(newTeacherList);

        return getDataTable(oldTeacherList);
    }

    /**
     * 查询当前教师相关的所有变更申请列表（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @GetMapping("/teacher/list")
    public TableDataInfo teacherList()
    {
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null)
        {
            return getDataTable(null);
        }

        startPage();
        List<TopicChangeRequest> list =
                topicChangeRequestService.selectChangeRequestListByTeacherId(teacherId);
        return getDataTable(list);
    }

    /**
     * 查询变更申请详情（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @GetMapping("/teacher/detail/{requestId}")
    public AjaxResult getTeacherDetail(@PathVariable Long requestId)
    {
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null)
        {
            return error("请先完善教师信息");
        }

        // 检查申请是否与该教师相关
        boolean isOldTeacher = topicChangeRequestService.checkRequestOldTeacher(requestId, teacherId);
        boolean isNewTeacher = topicChangeRequestService.checkRequestNewTeacher(requestId, teacherId);

        if (!isOldTeacher && !isNewTeacher)
        {
            return error("无权查看该申请");
        }

        TopicChangeRequest request = topicChangeRequestService.selectTopicChangeRequestByRequestId(requestId);
        return success(request);
    }

    /**
     * 原教师审核变更申请（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @Log(title = "原教师审核换题", businessType = BusinessType.UPDATE)
    @PutMapping("/teacher/reviewAsOld/{requestId}")
    public AjaxResult reviewAsOldTeacher(@PathVariable Long requestId,
                                         @RequestBody TopicChangeRequest request)
    {
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null)
        {
            return error("请先完善教师信息");
        }

        // 验证审核意见
        if (request.getOldTeacherOpinion() == null ||
                (!"同意".equals(request.getOldTeacherOpinion()) &&
                        !"拒绝".equals(request.getOldTeacherOpinion())))
        {
            return error("审核意见只能是「同意」或「拒绝」");
        }

        return toAjax(topicChangeRequestService.reviewByOldTeacher(
                requestId,
                teacherId,
                request.getOldTeacherOpinion(),
                request.getOldTeacherReason()
        ));
    }

    /**
     * 新教师审核变更申请（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @Log(title = "新教师审核换题", businessType = BusinessType.UPDATE)
    @PutMapping("/teacher/reviewAsNew/{requestId}")
    public AjaxResult reviewAsNewTeacher(@PathVariable Long requestId,
                                         @RequestBody TopicChangeRequest request)
    {
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null)
        {
            return error("请先完善教师信息");
        }

        // 验证审核意见
        if (request.getNewTeacherOpinion() == null ||
                (!"同意".equals(request.getNewTeacherOpinion()) &&
                        !"拒绝".equals(request.getNewTeacherOpinion())))
        {
            return error("审核意见只能是「同意」或「拒绝」");
        }

        return toAjax(topicChangeRequestService.reviewByNewTeacher(
                requestId,
                teacherId,
                request.getNewTeacherOpinion(),
                request.getNewTeacherReason()
        ));
    }

    /**
     * 导出教师相关的变更申请列表（教师端）
     */
    @PreAuthorize("@ss.hasRole('teacher')")
    @Log(title = "导出换题申请", businessType = BusinessType.EXPORT)
    @PostMapping("/teacher/export")
    public void export(HttpServletResponse response)
    {
        Long teacherId = getCurrentTeacherId();
        if (teacherId == null)
        {
            return;
        }

        List<TopicChangeRequest> list =
                topicChangeRequestService.selectChangeRequestListByTeacherId(teacherId);
        ExcelUtil<TopicChangeRequest> util = new ExcelUtil<TopicChangeRequest>(TopicChangeRequest.class);
        util.exportExcel(response, list, "选题变更申请数据");
    }

    // ==================== 管理员端接口 ====================

    /**
     * 查询所有选题变更申请列表（管理员端）
     */
    @PreAuthorize("@ss.hasRole('admin') or @ss.hasRole('administrator')")
    @GetMapping("/list")
    public TableDataInfo list(TopicChangeRequest topicChangeRequest)
    {
        startPage();
        List<TopicChangeRequest> list = topicChangeRequestService.selectTopicChangeRequestList(topicChangeRequest);
        return getDataTable(list);
    }

    /**
     * 获取选题变更申请详细信息（管理员端）
     */
    @PreAuthorize("@ss.hasRole('admin') or @ss.hasRole('administrator')")
    @GetMapping(value = "/{requestId}")
    public AjaxResult getInfo(@PathVariable("requestId") Long requestId)
    {
        return success(topicChangeRequestService.selectTopicChangeRequestByRequestId(requestId));
    }

    /**
     * 删除选题变更申请（管理员端）
     */
    @PreAuthorize("@ss.hasRole('admin') or @ss.hasRole('administrator')")
    @Log(title = "选题变更申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{requestIds}")
    public AjaxResult remove(@PathVariable Long[] requestIds)
    {
        return toAjax(topicChangeRequestService.deleteTopicChangeRequestByRequestIds(requestIds));
    }

    /**
     * 导出选题变更申请列表（管理员端）
     */
    @PreAuthorize("@ss.hasRole('admin') or @ss.hasRole('administrator')")
    @Log(title = "选题变更申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportAdmin(HttpServletResponse response, TopicChangeRequest topicChangeRequest)
    {
        List<TopicChangeRequest> list = topicChangeRequestService.selectTopicChangeRequestList(topicChangeRequest);
        ExcelUtil<TopicChangeRequest> util = new ExcelUtil<TopicChangeRequest>(TopicChangeRequest.class);
        util.exportExcel(response, list, "选题变更申请数据");
    }

    // ==================== 工具方法 ====================

    /**
     * 获取当前登录用户的学生ID
     */
    private Long getCurrentStudentId()
    {
        Long userId = getUserId();
        StudentInfo studentInfo = studentInfoService.selectStudentInfoByUserId(userId);
        return studentInfo != null ? studentInfo.getStudentId() : null;
    }

    /**
     * 获取当前登录用户的教师ID
     */
    private Long getCurrentTeacherId()
    {
        Long userId = getUserId();
        TeacherInfo teacherInfo = teacherInfoService.selectTeacherInfoByUserId(userId);
        return teacherInfo != null ? teacherInfo.getTeacherId() : null;
    }
}